Developing an AI application

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load and preprocess the image dataset
  • Train the image classifier on your dataset
  • Use the trained classifier to predict image content

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

First up is importing the packages you'll need. It's good practice to keep all the imports at the beginning of your code. As you work through this notebook and find you need to import a package, make sure to add the import up here.

In [123]:
# Imports here
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sb
import torch
import time
import os

from PIL import Image
from torch import nn
from torch import optim
from torchvision import datasets, transforms, models 

Load the data

Here you'll use torchvision to load the data (documentation). The data should be included alongside this notebook, otherwise you can download it here. The dataset is split into three parts, training, validation, and testing. For the training, you'll want to apply transformations such as random scaling, cropping, and flipping. This will help the network generalize leading to better performance. You'll also need to make sure the input data is resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet. For this you don't want any scaling or rotation transformations, but you'll need to resize then crop the images to the appropriate size.

The pre-trained networks you'll use were trained on the ImageNet dataset where each color channel was normalized separately. For all three sets you'll need to normalize the means and standard deviations of the images to what the network expects. For the means, it's [0.485, 0.456, 0.406] and for the standard deviations [0.229, 0.224, 0.225], calculated from the ImageNet images. These values will shift each color channel to be centered at 0 and range from -1 to 1.

In [17]:
data_dir = 'flowers'
train_dir = data_dir + '/train'
valid_dir = data_dir + '/valid'
test_dir = data_dir + '/test'
In [18]:
# TODO: Define your transforms for the training, validation, and testing sets
train_transforms = transforms.Compose([transforms.RandomRotation(30),
                                       transforms.RandomResizedCrop(224),
                                       transforms.RandomHorizontalFlip(),
                                       transforms.ToTensor(),
                                       transforms.Normalize([0.485, 0.456, 0.406],
                                                            [0.229, 0.224, 0.225])])


test_transforms = transforms.Compose([transforms.Resize(255),
                                      transforms.CenterCrop(224),
                                      transforms.ToTensor(),
                                      transforms.Normalize([0.485, 0.456, 0.406],
                                                           [0.229, 0.224, 0.225])])

valid_transforms = transforms.Compose([transforms.Resize(255),
                                      transforms.CenterCrop(224),
                                      transforms.ToTensor(),
                                      transforms.Normalize([0.485, 0.456, 0.406],
                                                           [0.229, 0.224, 0.225])])
# TODO: Load the datasets with ImageFolder
train_data = datasets.ImageFolder(train_dir, transform=train_transforms)
test_data = datasets.ImageFolder(test_dir, transform=test_transforms)
valid_data = datasets.ImageFolder(valid_dir, transform=valid_transforms)

# TODO: Using the image datasets and the trainforms, define the dataloaders
trainloader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)
testloader = torch.utils.data.DataLoader(test_data, batch_size=64)
validloader = torch.utils.data.DataLoader(valid_data, batch_size=64)

Label mapping

You'll also need to load in a mapping from category label to category name. You can find this in the file cat_to_name.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer encoded categories to the actual names of the flowers.

In [19]:
import json

with open('cat_to_name.json', 'r') as f:
    cat_to_name = json.load(f)
    

Building and training the classifier

Now that the data is ready, it's time to build and train the classifier. As usual, you should use one of the pretrained models from torchvision.models to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load a pre-trained network (If you need a starting point, the VGG networks work great and are straightforward to use)
  • Define a new, untrained feed-forward network as a classifier, using ReLU activations and dropout
  • Train the classifier layers using backpropagation using the pre-trained network to get the features
  • Track the loss and accuracy on the validation set to determine the best hyperparameters

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right. Make sure to try different hyperparameters (learning rate, units in the classifier, epochs, etc) to find the best model. Save those hyperparameters to use as default values in the next part of the project.

One last important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module.

**Note for Workspace users:** If your network is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. Typically this happens with wide dense layers after the convolutional layers. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with `ls -lh`), you should reduce the size of your hidden layers and train again.

In [20]:
# TODO: Build and train your network

# Use GPU if it is available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
In [21]:
#Load pretrained model

model = models.vgg16(pretrained=True)

model
Out[21]:
VGG(
  (features): Sequential(
    (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU(inplace)
    (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU(inplace)
    (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (6): ReLU(inplace)
    (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (8): ReLU(inplace)
    (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (11): ReLU(inplace)
    (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (13): ReLU(inplace)
    (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (15): ReLU(inplace)
    (16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (18): ReLU(inplace)
    (19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (20): ReLU(inplace)
    (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (22): ReLU(inplace)
    (23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (25): ReLU(inplace)
    (26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (27): ReLU(inplace)
    (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (29): ReLU(inplace)
    (30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (classifier): Sequential(
    (0): Linear(in_features=25088, out_features=4096, bias=True)
    (1): ReLU(inplace)
    (2): Dropout(p=0.5)
    (3): Linear(in_features=4096, out_features=4096, bias=True)
    (4): ReLU(inplace)
    (5): Dropout(p=0.5)
    (6): Linear(in_features=4096, out_features=1000, bias=True)
  )
)
In [22]:
# Freeze parameters
for param in model.parameters():
    param.requires_grad = False
    
In [23]:
#Build model    
model.classifier = nn.Sequential(nn.Linear(25088, 2048),
                                 nn.ReLU(),
                                 nn.Dropout(0.2),
                                 nn.Linear(2048, 1024),
                                 nn.ReLU(),
                                 nn.Dropout(0.2),
                                 nn.Linear(1024, 102),
                                 nn.LogSoftmax(dim=1))

criterion = nn.NLLLoss()

# Only train the classifier parameters, feature parameters are frozen
optimizer = optim.Adam(model.classifier.parameters(), lr=0.003)

model.to(device);
In [24]:
#Train
   
epochs = 10
steps = 0
running_loss = 0
print_every = 5
for epoch in range(epochs):
    for inputs, labels in trainloader:
        steps += 1
        # Move input and label tensors to the default device
        inputs, labels = inputs.to(device), labels.to(device)
        
        optimizer.zero_grad()
        
        logps = model.forward(inputs)
        loss = criterion(logps, labels)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        
        if steps % print_every == 0:
            valid_loss = 0
            accuracy = 0
            model.eval()
            with torch.no_grad():
                for inputs, labels in validloader:
                    inputs, labels = inputs.to(device), labels.to(device)
                    logps = model.forward(inputs)
                    batch_loss = criterion(logps, labels)
                    
                    valid_loss += batch_loss.item()
                    
                    # Calculate accuracy
                    ps = torch.exp(logps)
                    top_p, top_class = ps.topk(1, dim=1)
                    equals = top_class == labels.view(*top_class.shape)
                    accuracy += torch.mean(equals.type(torch.FloatTensor)).item()
                    
            print(f"Epoch {epoch+1}/{epochs}.. "
                  f"Train loss: {running_loss/print_every:.3f}.. "
                  f"Validation loss: {valid_loss/len(validloader):.3f}.. "
                  f"Validation accuracy: {accuracy/len(validloader):.3f}")
            running_loss = 0
            model.train()
Epoch 1/10.. Train loss: 11.978.. Validation loss: 4.787.. Validation accuracy: 0.053
Epoch 1/10.. Train loss: 4.513.. Validation loss: 4.403.. Validation accuracy: 0.083
Epoch 1/10.. Train loss: 4.369.. Validation loss: 4.130.. Validation accuracy: 0.133
Epoch 1/10.. Train loss: 4.163.. Validation loss: 3.773.. Validation accuracy: 0.170
Epoch 1/10.. Train loss: 4.060.. Validation loss: 3.427.. Validation accuracy: 0.223
Epoch 1/10.. Train loss: 3.766.. Validation loss: 3.196.. Validation accuracy: 0.242
Epoch 1/10.. Train loss: 3.622.. Validation loss: 2.961.. Validation accuracy: 0.294
Epoch 1/10.. Train loss: 3.279.. Validation loss: 2.771.. Validation accuracy: 0.302
Epoch 1/10.. Train loss: 3.124.. Validation loss: 2.645.. Validation accuracy: 0.334
Epoch 1/10.. Train loss: 3.127.. Validation loss: 2.588.. Validation accuracy: 0.357
Epoch 1/10.. Train loss: 2.975.. Validation loss: 2.430.. Validation accuracy: 0.393
Epoch 1/10.. Train loss: 2.937.. Validation loss: 2.263.. Validation accuracy: 0.406
Epoch 1/10.. Train loss: 3.087.. Validation loss: 2.253.. Validation accuracy: 0.437
Epoch 1/10.. Train loss: 2.895.. Validation loss: 2.162.. Validation accuracy: 0.431
Epoch 1/10.. Train loss: 2.683.. Validation loss: 2.082.. Validation accuracy: 0.455
Epoch 1/10.. Train loss: 2.835.. Validation loss: 2.031.. Validation accuracy: 0.453
Epoch 1/10.. Train loss: 2.616.. Validation loss: 1.968.. Validation accuracy: 0.469
Epoch 1/10.. Train loss: 2.807.. Validation loss: 1.833.. Validation accuracy: 0.512
Epoch 1/10.. Train loss: 2.645.. Validation loss: 1.857.. Validation accuracy: 0.502
Epoch 1/10.. Train loss: 2.890.. Validation loss: 1.847.. Validation accuracy: 0.524
Epoch 2/10.. Train loss: 2.505.. Validation loss: 1.991.. Validation accuracy: 0.496
Epoch 2/10.. Train loss: 2.512.. Validation loss: 1.844.. Validation accuracy: 0.532
Epoch 2/10.. Train loss: 2.515.. Validation loss: 1.902.. Validation accuracy: 0.516
Epoch 2/10.. Train loss: 2.660.. Validation loss: 1.769.. Validation accuracy: 0.526
Epoch 2/10.. Train loss: 2.706.. Validation loss: 1.734.. Validation accuracy: 0.536
Epoch 2/10.. Train loss: 2.609.. Validation loss: 1.749.. Validation accuracy: 0.535
Epoch 2/10.. Train loss: 2.547.. Validation loss: 1.752.. Validation accuracy: 0.534
Epoch 2/10.. Train loss: 2.405.. Validation loss: 1.649.. Validation accuracy: 0.555
Epoch 2/10.. Train loss: 2.588.. Validation loss: 1.662.. Validation accuracy: 0.565
Epoch 2/10.. Train loss: 2.534.. Validation loss: 1.615.. Validation accuracy: 0.573
Epoch 2/10.. Train loss: 2.366.. Validation loss: 1.611.. Validation accuracy: 0.574
Epoch 2/10.. Train loss: 2.687.. Validation loss: 1.695.. Validation accuracy: 0.532
Epoch 2/10.. Train loss: 2.822.. Validation loss: 1.735.. Validation accuracy: 0.540
Epoch 2/10.. Train loss: 2.601.. Validation loss: 1.628.. Validation accuracy: 0.565
Epoch 2/10.. Train loss: 2.458.. Validation loss: 1.590.. Validation accuracy: 0.596
Epoch 2/10.. Train loss: 2.513.. Validation loss: 1.526.. Validation accuracy: 0.619
Epoch 2/10.. Train loss: 2.312.. Validation loss: 1.587.. Validation accuracy: 0.593
Epoch 2/10.. Train loss: 2.369.. Validation loss: 1.478.. Validation accuracy: 0.617
Epoch 2/10.. Train loss: 2.063.. Validation loss: 1.478.. Validation accuracy: 0.613
Epoch 2/10.. Train loss: 2.500.. Validation loss: 1.462.. Validation accuracy: 0.606
Epoch 2/10.. Train loss: 2.359.. Validation loss: 1.473.. Validation accuracy: 0.620
Epoch 3/10.. Train loss: 2.241.. Validation loss: 1.525.. Validation accuracy: 0.602
Epoch 3/10.. Train loss: 2.430.. Validation loss: 1.460.. Validation accuracy: 0.616
Epoch 3/10.. Train loss: 2.195.. Validation loss: 1.490.. Validation accuracy: 0.607
Epoch 3/10.. Train loss: 2.343.. Validation loss: 1.460.. Validation accuracy: 0.620
Epoch 3/10.. Train loss: 2.298.. Validation loss: 1.565.. Validation accuracy: 0.608
Epoch 3/10.. Train loss: 2.254.. Validation loss: 1.455.. Validation accuracy: 0.609
Epoch 3/10.. Train loss: 2.277.. Validation loss: 1.331.. Validation accuracy: 0.645
Epoch 3/10.. Train loss: 2.287.. Validation loss: 1.417.. Validation accuracy: 0.623
Epoch 3/10.. Train loss: 2.488.. Validation loss: 1.336.. Validation accuracy: 0.647
Epoch 3/10.. Train loss: 2.190.. Validation loss: 1.509.. Validation accuracy: 0.608
Epoch 3/10.. Train loss: 2.170.. Validation loss: 1.446.. Validation accuracy: 0.617
Epoch 3/10.. Train loss: 2.301.. Validation loss: 1.326.. Validation accuracy: 0.675
Epoch 3/10.. Train loss: 2.039.. Validation loss: 1.305.. Validation accuracy: 0.684
Epoch 3/10.. Train loss: 2.149.. Validation loss: 1.361.. Validation accuracy: 0.650
Epoch 3/10.. Train loss: 2.344.. Validation loss: 1.318.. Validation accuracy: 0.651
Epoch 3/10.. Train loss: 2.121.. Validation loss: 1.367.. Validation accuracy: 0.657
Epoch 3/10.. Train loss: 2.501.. Validation loss: 1.355.. Validation accuracy: 0.647
Epoch 3/10.. Train loss: 2.213.. Validation loss: 1.327.. Validation accuracy: 0.659
Epoch 3/10.. Train loss: 2.267.. Validation loss: 1.387.. Validation accuracy: 0.668
Epoch 3/10.. Train loss: 2.134.. Validation loss: 1.328.. Validation accuracy: 0.670
Epoch 4/10.. Train loss: 2.241.. Validation loss: 1.294.. Validation accuracy: 0.655
Epoch 4/10.. Train loss: 2.240.. Validation loss: 1.246.. Validation accuracy: 0.659
Epoch 4/10.. Train loss: 2.074.. Validation loss: 1.265.. Validation accuracy: 0.659
Epoch 4/10.. Train loss: 2.172.. Validation loss: 1.322.. Validation accuracy: 0.650
Epoch 4/10.. Train loss: 2.220.. Validation loss: 1.324.. Validation accuracy: 0.634
Epoch 4/10.. Train loss: 2.038.. Validation loss: 1.374.. Validation accuracy: 0.632
Epoch 4/10.. Train loss: 2.026.. Validation loss: 1.333.. Validation accuracy: 0.646
Epoch 4/10.. Train loss: 2.201.. Validation loss: 1.227.. Validation accuracy: 0.677
Epoch 4/10.. Train loss: 2.214.. Validation loss: 1.319.. Validation accuracy: 0.647
Epoch 4/10.. Train loss: 2.131.. Validation loss: 1.336.. Validation accuracy: 0.654
Epoch 4/10.. Train loss: 2.197.. Validation loss: 1.239.. Validation accuracy: 0.679
Epoch 4/10.. Train loss: 2.322.. Validation loss: 1.267.. Validation accuracy: 0.641
Epoch 4/10.. Train loss: 2.062.. Validation loss: 1.250.. Validation accuracy: 0.646
Epoch 4/10.. Train loss: 2.150.. Validation loss: 1.171.. Validation accuracy: 0.674
Epoch 4/10.. Train loss: 1.901.. Validation loss: 1.181.. Validation accuracy: 0.673
Epoch 4/10.. Train loss: 2.176.. Validation loss: 1.253.. Validation accuracy: 0.650
Epoch 4/10.. Train loss: 2.301.. Validation loss: 1.253.. Validation accuracy: 0.655
Epoch 4/10.. Train loss: 2.039.. Validation loss: 1.260.. Validation accuracy: 0.654
Epoch 4/10.. Train loss: 2.050.. Validation loss: 1.244.. Validation accuracy: 0.673
Epoch 4/10.. Train loss: 2.102.. Validation loss: 1.406.. Validation accuracy: 0.637
Epoch 4/10.. Train loss: 2.253.. Validation loss: 1.267.. Validation accuracy: 0.656
Epoch 5/10.. Train loss: 2.286.. Validation loss: 1.279.. Validation accuracy: 0.661
Epoch 5/10.. Train loss: 2.078.. Validation loss: 1.212.. Validation accuracy: 0.680
Epoch 5/10.. Train loss: 1.905.. Validation loss: 1.185.. Validation accuracy: 0.691
Epoch 5/10.. Train loss: 2.098.. Validation loss: 1.216.. Validation accuracy: 0.678
Epoch 5/10.. Train loss: 1.959.. Validation loss: 1.269.. Validation accuracy: 0.663
Epoch 5/10.. Train loss: 2.093.. Validation loss: 1.313.. Validation accuracy: 0.643
Epoch 5/10.. Train loss: 2.236.. Validation loss: 1.334.. Validation accuracy: 0.670
Epoch 5/10.. Train loss: 2.037.. Validation loss: 1.328.. Validation accuracy: 0.674
Epoch 5/10.. Train loss: 2.198.. Validation loss: 1.300.. Validation accuracy: 0.655
Epoch 5/10.. Train loss: 1.935.. Validation loss: 1.234.. Validation accuracy: 0.676
Epoch 5/10.. Train loss: 2.106.. Validation loss: 1.141.. Validation accuracy: 0.701
Epoch 5/10.. Train loss: 1.972.. Validation loss: 1.161.. Validation accuracy: 0.691
Epoch 5/10.. Train loss: 1.967.. Validation loss: 1.267.. Validation accuracy: 0.647
Epoch 5/10.. Train loss: 2.094.. Validation loss: 1.207.. Validation accuracy: 0.666
Epoch 5/10.. Train loss: 1.963.. Validation loss: 1.136.. Validation accuracy: 0.699
Epoch 5/10.. Train loss: 2.167.. Validation loss: 1.230.. Validation accuracy: 0.679
Epoch 5/10.. Train loss: 1.959.. Validation loss: 1.190.. Validation accuracy: 0.688
Epoch 5/10.. Train loss: 2.064.. Validation loss: 1.108.. Validation accuracy: 0.692
Epoch 5/10.. Train loss: 2.023.. Validation loss: 1.110.. Validation accuracy: 0.693
Epoch 5/10.. Train loss: 1.862.. Validation loss: 1.163.. Validation accuracy: 0.690
Epoch 5/10.. Train loss: 2.097.. Validation loss: 1.254.. Validation accuracy: 0.670
Epoch 6/10.. Train loss: 1.874.. Validation loss: 1.276.. Validation accuracy: 0.682
Epoch 6/10.. Train loss: 1.913.. Validation loss: 1.171.. Validation accuracy: 0.696
Epoch 6/10.. Train loss: 2.014.. Validation loss: 1.091.. Validation accuracy: 0.718
Epoch 6/10.. Train loss: 1.855.. Validation loss: 1.157.. Validation accuracy: 0.689
Epoch 6/10.. Train loss: 2.211.. Validation loss: 1.160.. Validation accuracy: 0.692
Epoch 6/10.. Train loss: 2.122.. Validation loss: 1.125.. Validation accuracy: 0.711
Epoch 6/10.. Train loss: 1.908.. Validation loss: 1.185.. Validation accuracy: 0.693
Epoch 6/10.. Train loss: 1.945.. Validation loss: 1.191.. Validation accuracy: 0.691
Epoch 6/10.. Train loss: 2.185.. Validation loss: 1.113.. Validation accuracy: 0.712
Epoch 6/10.. Train loss: 2.050.. Validation loss: 1.137.. Validation accuracy: 0.693
Epoch 6/10.. Train loss: 1.906.. Validation loss: 1.134.. Validation accuracy: 0.690
Epoch 6/10.. Train loss: 2.007.. Validation loss: 1.098.. Validation accuracy: 0.705
Epoch 6/10.. Train loss: 2.030.. Validation loss: 1.097.. Validation accuracy: 0.700
Epoch 6/10.. Train loss: 1.948.. Validation loss: 1.128.. Validation accuracy: 0.702
Epoch 6/10.. Train loss: 2.126.. Validation loss: 1.090.. Validation accuracy: 0.710
Epoch 6/10.. Train loss: 1.961.. Validation loss: 1.077.. Validation accuracy: 0.696
Epoch 6/10.. Train loss: 1.947.. Validation loss: 1.157.. Validation accuracy: 0.687
Epoch 6/10.. Train loss: 1.901.. Validation loss: 1.120.. Validation accuracy: 0.688
Epoch 6/10.. Train loss: 2.114.. Validation loss: 1.113.. Validation accuracy: 0.701
Epoch 6/10.. Train loss: 1.839.. Validation loss: 1.150.. Validation accuracy: 0.697
Epoch 7/10.. Train loss: 2.050.. Validation loss: 1.133.. Validation accuracy: 0.684
Epoch 7/10.. Train loss: 1.867.. Validation loss: 1.146.. Validation accuracy: 0.700
Epoch 7/10.. Train loss: 1.993.. Validation loss: 1.171.. Validation accuracy: 0.679
Epoch 7/10.. Train loss: 1.898.. Validation loss: 1.112.. Validation accuracy: 0.692
Epoch 7/10.. Train loss: 1.864.. Validation loss: 1.147.. Validation accuracy: 0.679
Epoch 7/10.. Train loss: 2.074.. Validation loss: 1.185.. Validation accuracy: 0.681
Epoch 7/10.. Train loss: 2.037.. Validation loss: 1.149.. Validation accuracy: 0.688
Epoch 7/10.. Train loss: 2.031.. Validation loss: 1.121.. Validation accuracy: 0.689
Epoch 7/10.. Train loss: 1.839.. Validation loss: 1.133.. Validation accuracy: 0.698
Epoch 7/10.. Train loss: 1.986.. Validation loss: 1.126.. Validation accuracy: 0.699
Epoch 7/10.. Train loss: 2.043.. Validation loss: 1.202.. Validation accuracy: 0.704
Epoch 7/10.. Train loss: 1.920.. Validation loss: 1.219.. Validation accuracy: 0.690
Epoch 7/10.. Train loss: 2.020.. Validation loss: 1.190.. Validation accuracy: 0.674
Epoch 7/10.. Train loss: 2.038.. Validation loss: 1.125.. Validation accuracy: 0.682
Epoch 7/10.. Train loss: 1.738.. Validation loss: 1.115.. Validation accuracy: 0.687
Epoch 7/10.. Train loss: 2.282.. Validation loss: 1.083.. Validation accuracy: 0.692
Epoch 7/10.. Train loss: 1.946.. Validation loss: 1.155.. Validation accuracy: 0.687
Epoch 7/10.. Train loss: 1.843.. Validation loss: 1.163.. Validation accuracy: 0.694
Epoch 7/10.. Train loss: 2.040.. Validation loss: 1.098.. Validation accuracy: 0.705
Epoch 7/10.. Train loss: 2.027.. Validation loss: 1.129.. Validation accuracy: 0.696
Epoch 7/10.. Train loss: 2.067.. Validation loss: 1.142.. Validation accuracy: 0.692
Epoch 8/10.. Train loss: 1.996.. Validation loss: 1.239.. Validation accuracy: 0.684
Epoch 8/10.. Train loss: 2.010.. Validation loss: 1.094.. Validation accuracy: 0.709
Epoch 8/10.. Train loss: 1.790.. Validation loss: 1.048.. Validation accuracy: 0.720
Epoch 8/10.. Train loss: 1.975.. Validation loss: 1.050.. Validation accuracy: 0.713
Epoch 8/10.. Train loss: 1.895.. Validation loss: 1.132.. Validation accuracy: 0.694
Epoch 8/10.. Train loss: 1.898.. Validation loss: 1.179.. Validation accuracy: 0.681
Epoch 8/10.. Train loss: 2.008.. Validation loss: 1.132.. Validation accuracy: 0.698
Epoch 8/10.. Train loss: 2.046.. Validation loss: 1.150.. Validation accuracy: 0.680
Epoch 8/10.. Train loss: 2.112.. Validation loss: 1.229.. Validation accuracy: 0.665
Epoch 8/10.. Train loss: 2.179.. Validation loss: 1.232.. Validation accuracy: 0.669
Epoch 8/10.. Train loss: 2.181.. Validation loss: 1.230.. Validation accuracy: 0.673
Epoch 8/10.. Train loss: 2.121.. Validation loss: 1.177.. Validation accuracy: 0.674
Epoch 8/10.. Train loss: 1.959.. Validation loss: 1.178.. Validation accuracy: 0.686
Epoch 8/10.. Train loss: 2.051.. Validation loss: 1.126.. Validation accuracy: 0.699
Epoch 8/10.. Train loss: 1.988.. Validation loss: 1.141.. Validation accuracy: 0.695
Epoch 8/10.. Train loss: 1.778.. Validation loss: 1.113.. Validation accuracy: 0.695
Epoch 8/10.. Train loss: 1.801.. Validation loss: 1.102.. Validation accuracy: 0.706
Epoch 8/10.. Train loss: 1.946.. Validation loss: 1.056.. Validation accuracy: 0.736
Epoch 8/10.. Train loss: 1.980.. Validation loss: 1.077.. Validation accuracy: 0.716
Epoch 8/10.. Train loss: 1.992.. Validation loss: 1.132.. Validation accuracy: 0.702
Epoch 9/10.. Train loss: 2.085.. Validation loss: 1.119.. Validation accuracy: 0.695
Epoch 9/10.. Train loss: 1.763.. Validation loss: 1.135.. Validation accuracy: 0.683
Epoch 9/10.. Train loss: 1.723.. Validation loss: 1.143.. Validation accuracy: 0.693
Epoch 9/10.. Train loss: 1.985.. Validation loss: 1.116.. Validation accuracy: 0.696
Epoch 9/10.. Train loss: 1.979.. Validation loss: 1.107.. Validation accuracy: 0.712
Epoch 9/10.. Train loss: 1.943.. Validation loss: 1.149.. Validation accuracy: 0.706
Epoch 9/10.. Train loss: 1.916.. Validation loss: 1.096.. Validation accuracy: 0.726
Epoch 9/10.. Train loss: 1.951.. Validation loss: 1.122.. Validation accuracy: 0.701
Epoch 9/10.. Train loss: 1.839.. Validation loss: 1.112.. Validation accuracy: 0.694
Epoch 9/10.. Train loss: 1.881.. Validation loss: 1.117.. Validation accuracy: 0.723
Epoch 9/10.. Train loss: 2.038.. Validation loss: 1.072.. Validation accuracy: 0.724
Epoch 9/10.. Train loss: 1.951.. Validation loss: 1.096.. Validation accuracy: 0.715
Epoch 9/10.. Train loss: 2.048.. Validation loss: 1.119.. Validation accuracy: 0.715
Epoch 9/10.. Train loss: 1.972.. Validation loss: 1.116.. Validation accuracy: 0.715
Epoch 9/10.. Train loss: 2.024.. Validation loss: 1.150.. Validation accuracy: 0.710
Epoch 9/10.. Train loss: 2.194.. Validation loss: 1.151.. Validation accuracy: 0.712
Epoch 9/10.. Train loss: 1.719.. Validation loss: 1.103.. Validation accuracy: 0.711
Epoch 9/10.. Train loss: 2.031.. Validation loss: 1.042.. Validation accuracy: 0.720
Epoch 9/10.. Train loss: 1.945.. Validation loss: 1.081.. Validation accuracy: 0.719
Epoch 9/10.. Train loss: 2.014.. Validation loss: 1.105.. Validation accuracy: 0.710
Epoch 9/10.. Train loss: 1.933.. Validation loss: 1.078.. Validation accuracy: 0.707
Epoch 10/10.. Train loss: 1.788.. Validation loss: 1.032.. Validation accuracy: 0.719
Epoch 10/10.. Train loss: 1.816.. Validation loss: 1.026.. Validation accuracy: 0.729
Epoch 10/10.. Train loss: 1.809.. Validation loss: 1.002.. Validation accuracy: 0.727
Epoch 10/10.. Train loss: 1.629.. Validation loss: 1.001.. Validation accuracy: 0.747
Epoch 10/10.. Train loss: 1.975.. Validation loss: 1.010.. Validation accuracy: 0.723
Epoch 10/10.. Train loss: 1.897.. Validation loss: 0.927.. Validation accuracy: 0.738
Epoch 10/10.. Train loss: 1.912.. Validation loss: 0.978.. Validation accuracy: 0.738
Epoch 10/10.. Train loss: 2.210.. Validation loss: 1.027.. Validation accuracy: 0.739
Epoch 10/10.. Train loss: 1.960.. Validation loss: 1.120.. Validation accuracy: 0.704
Epoch 10/10.. Train loss: 1.826.. Validation loss: 1.154.. Validation accuracy: 0.702
Epoch 10/10.. Train loss: 1.870.. Validation loss: 1.104.. Validation accuracy: 0.719
Epoch 10/10.. Train loss: 1.910.. Validation loss: 1.121.. Validation accuracy: 0.716
Epoch 10/10.. Train loss: 1.768.. Validation loss: 1.092.. Validation accuracy: 0.719
Epoch 10/10.. Train loss: 2.154.. Validation loss: 0.985.. Validation accuracy: 0.736
Epoch 10/10.. Train loss: 1.913.. Validation loss: 0.977.. Validation accuracy: 0.746
Epoch 10/10.. Train loss: 1.879.. Validation loss: 0.961.. Validation accuracy: 0.747
Epoch 10/10.. Train loss: 1.941.. Validation loss: 0.937.. Validation accuracy: 0.741
Epoch 10/10.. Train loss: 1.811.. Validation loss: 0.939.. Validation accuracy: 0.723
Epoch 10/10.. Train loss: 1.739.. Validation loss: 0.954.. Validation accuracy: 0.731
Epoch 10/10.. Train loss: 1.787.. Validation loss: 0.981.. Validation accuracy: 0.732
Epoch 10/10.. Train loss: 2.175.. Validation loss: 1.055.. Validation accuracy: 0.709

Testing your network

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. Run the test images through the network and measure the accuracy, the same way you did validation. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [25]:
# TODO: Do validation on the test set

#Test
            
test_loss = 0
accuracy = 0
model.eval()
        
with torch.no_grad():
    for inputs, labels in testloader:
        inputs, labels = inputs.to(device), labels.to(device)
        logps = model.forward(inputs)
        batch_loss = criterion(logps, labels)
                    
        test_loss += batch_loss.item()
                    
        # Calculate accuracy
        ps = torch.exp(logps)
        top_p, top_class = ps.topk(1, dim=1)
        equals = top_class == labels.view(*top_class.shape)
        accuracy += torch.mean(equals.type(torch.FloatTensor)).item()
                    
print(f"Test loss: {test_loss/len(testloader):.3f}.. "
      f"Test accuracy: {100 * accuracy/len(testloader):.3f} %")
Test loss: 1.100.. Test accuracy: 71.529 %

Save the checkpoint

Now that your network is trained, save the model so you can load it later for making predictions. You probably want to save other things such as the mapping of classes to indices which you get from one of the image datasets: image_datasets['train'].class_to_idx. You can attach this to the model as an attribute which makes inference easier later on.

model.class_to_idx = image_datasets['train'].class_to_idx

Remember that you'll want to completely rebuild the model later so you can use it for inference. Make sure to include any information you need in the checkpoint. If you want to load the model and keep training, you'll want to save the number of epochs as well as the optimizer state, optimizer.state_dict. You'll likely want to use this trained model in the next part of the project, so best to save it now.

In [26]:
# TODO: Save the checkpoint

model.class_to_idx = train_data.class_to_idx

checkpoint = {'input_size': 25088,
              'output_size': 102,
              'hidden_layer1': 2048,
              'hidden_layer2': 1024,
              'epochs': epochs,
              'class_to_idx_mapping': model.class_to_idx,
              'optimizer_state': optimizer.state_dict(),
              'state_dict': model.state_dict()}

torch.save(checkpoint, 'checkpoint.pth')

Loading the checkpoint

At this point it's good to write a function that can load a checkpoint and rebuild the model. That way you can come back to this project and keep working on it without having to retrain the network.

In [34]:
# TODO: Write a function that loads a checkpoint and rebuilds the model

def load_checkpoint(filepath):
    
    checkpoint = torch.load(filepath)
    model.load_state_dict(checkpoint['state_dict'])
    optimizer.load_state_dict(checkpoint['optimizer_state'])
    
    input_size = checkpoint['input_size']
    output_size = checkpoint['output_size']
    hidden_layer1 = checkpoint['hidden_layer1']
    hidden_layer2 = checkpoint['hidden_layer2']
    epochs = checkpoint['epochs']
    
    return model, optimizer, input_size, output_size, epochs
In [36]:
filepath = 'checkpoint.pth'
reloaded_model, reloaded_optimizer, input_size, output_size, epochs = load_checkpoint(filepath)

print(reloaded_model)
print(reloaded_optimizer)
print(input_size)
print(output_size)
print(epochs)
VGG(
  (features): Sequential(
    (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU(inplace)
    (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU(inplace)
    (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (6): ReLU(inplace)
    (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (8): ReLU(inplace)
    (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (11): ReLU(inplace)
    (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (13): ReLU(inplace)
    (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (15): ReLU(inplace)
    (16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (18): ReLU(inplace)
    (19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (20): ReLU(inplace)
    (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (22): ReLU(inplace)
    (23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (25): ReLU(inplace)
    (26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (27): ReLU(inplace)
    (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (29): ReLU(inplace)
    (30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (classifier): Sequential(
    (0): Linear(in_features=25088, out_features=2048, bias=True)
    (1): ReLU()
    (2): Dropout(p=0.2)
    (3): Linear(in_features=2048, out_features=1024, bias=True)
    (4): ReLU()
    (5): Dropout(p=0.2)
    (6): Linear(in_features=1024, out_features=102, bias=True)
    (7): LogSoftmax()
  )
)
Adam (
Parameter Group 0
    amsgrad: False
    betas: (0.9, 0.999)
    eps: 1e-08
    lr: 0.003
    weight_decay: 0
)
25088
102
10

Inference for classification

Now you'll write a function to use a trained network for inference. That is, you'll pass an image into the network and predict the class of the flower in the image. Write a function called predict that takes an image and a model, then returns the top $K$ most likely classes along with the probabilities. It should look like

probs, classes = predict(image_path, model)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

First you'll need to handle processing the input image such that it can be used in your network.

Image Preprocessing

You'll want to use PIL to load the image (documentation). It's best to write a function that preprocesses the image so it can be used as input for the model. This function should process the images in the same manner used for training.

First, resize the images where the shortest side is 256 pixels, keeping the aspect ratio. This can be done with the thumbnail or resize methods. Then you'll need to crop out the center 224x224 portion of the image.

Color channels of images are typically encoded as integers 0-255, but the model expected floats 0-1. You'll need to convert the values. It's easiest with a Numpy array, which you can get from a PIL image like so np_image = np.array(pil_image).

As before, the network expects the images to be normalized in a specific way. For the means, it's [0.485, 0.456, 0.406] and for the standard deviations [0.229, 0.224, 0.225]. You'll want to subtract the means from each color channel, then divide by the standard deviation.

And finally, PyTorch expects the color channel to be the first dimension but it's the third dimension in the PIL image and Numpy array. You can reorder dimensions using ndarray.transpose. The color channel needs to be first and retain the order of the other two dimensions.

In [37]:
def process_image(image):
    ''' Scales, crops, and normalizes a PIL image for a PyTorch model,
        returns an Numpy array
    '''
    # TODO: Process a PIL image for use in a PyTorch model
    
    image = Image.open(image)
    image.load()
        
    # Scale image
    width, height = image.size
    if width < height:
        image.thumbnail((256, 256 * height // width))
    else:
        image.thumbnail((256 * width // height, 256))
    
    # Crop
    width, height = image.size
    left = (width - 224) // 2
    top = (height - 224) // 2
    right = (width + 224) // 2
    bottom = (height + 224) // 2
    image = image.crop((left, top, right, bottom))
    
    # Convert image to a numpy array
    np_image = np.array(image) / 255.0
    mean = np.array([0.485, 0.456, 0.406])
    std = np.array([0.229, 0.224, 0.225])
    np_image = (np_image - mean) / std
    
    # Transpose the color channel to the first dimension
    np_image = np_image.transpose((2, 0, 1))
    
    return np_image
In [38]:
image_path = 'flowers/test/13/image_05775.jpg'
processed_img = process_image(image_path)
Image.open(image_path)
Out[38]:

To check your work, the function below converts a PyTorch tensor and displays it in the notebook. If your process_image function works, running the output through this function should return the original image (except for the cropped out portions).

In [39]:
def imshow(image, ax=None, title=None):
    """Imshow for Tensor."""
    if ax is None:
        fig, ax = plt.subplots()
    
    # PyTorch tensors assume the color channel is the first dimension
    # but matplotlib assumes is the third dimension
    image = image.numpy().transpose((1, 2, 0))
    
    # Undo preprocessing
    mean = np.array([0.485, 0.456, 0.406])
    std = np.array([0.229, 0.224, 0.225])
    image = std * image + mean
    
    # Image needs to be clipped between 0 and 1 or it looks like noise when displayed
    image = np.clip(image, 0, 1)
    
    ax.imshow(image)
    
    return ax
In [40]:
imshow(torch.tensor(processed_img))
Out[40]:
<matplotlib.axes._subplots.AxesSubplot at 0x7fb821131a90>

Class Prediction

Once you can get images in the correct format, it's time to write a function for making predictions with your model. A common practice is to predict the top 5 or so (usually called top-$K$) most probable classes. You'll want to calculate the class probabilities then find the $K$ largest values.

To get the top $K$ largest values in a tensor use x.topk(k). This method returns both the highest k probabilities and the indices of those probabilities corresponding to the classes. You need to convert from these indices to the actual class labels using class_to_idx which hopefully you added to the model or from an ImageFolder you used to load the data (see here). Make sure to invert the dictionary so you get a mapping from index to class as well.

Again, this method should take a path to an image and a model checkpoint, then return the probabilities and classes.

probs, classes = predict(image_path, model)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']
In [143]:
def predict(image_path, model, topk=5):
    ''' Predict the class (or classes) of an image using a trained deep learning model.
    '''
    
    # TODO: Implement the code to predict the class from an image file
   
    model.to(device)
    model.eval()
    
    # Preprocessing the image
    img = process_image(image_path)
   
    
    # Convert image to a tensor
    tensor_img = torch.from_numpy(img).type(torch.FloatTensor)
    
    # Add a batch dimension to the image
    processed_img = tensor_img.unsqueeze_(0)
    processed_img = torch.tensor(processed_img)
    # Forward pass
    image = processed_img.to(device)
    output = model.forward(image)
    
    # Calculate the class probabilities
    probs = torch.exp(output)
    
    # Get the topk largest values and their indices
    top_probs, top_labels = probs.topk(topk)
       
    # Convert indices to classes
    idx_to_class = {val: key for key, val in model.class_to_idx.items()}
    top_labels = [idx_to_class[label] for label in top_labels.cpu().numpy()[0]]
    
    
    return top_probs.detach().cpu().numpy()[0], top_labels
In [144]:
probs, classes = predict(image_path, model)
print(probs)
print(classes)
[  9.99631464e-01   3.36321740e-04   1.56115857e-05   4.61144100e-06
   3.73245780e-06]
['13', '23', '35', '77', '14']

Sanity Checking

Now that you can use a trained model for predictions, check to make sure it makes sense. Even if the testing accuracy is high, it's always good to check that there aren't obvious bugs. Use matplotlib to plot the probabilities for the top 5 classes as a bar graph, along with the input image. It should look like this:

You can convert from the class integer encoding to actual flower names with the cat_to_name.json file (should have been loaded earlier in the notebook). To show a PyTorch tensor as an image, use the imshow function defined above.

In [151]:
# TODO: Display an image along with the top 5 classes

def sanity_checker(image_path, mapper):
    # Get the top 5 classes and corresponding probabilities

    top_probs, top_labels = predict(image_path, model)

    # Convert the labels to strings
    top_labels = [mapper[label] for label in top_labels]

    print(top_probs)
    print(top_labels)
    
    # Get the file name without the extension
    filename =  image_path.split('/')[-2]
    
    # Remove the file extension from the file name
    flower_title = mapper[filename]

    # Load the image
    image = Image.open(image_path)
    

    # Convert the image to a NumPy array
    image = np.array(image)

    # Invert the image
    image[:,:,0] = 255 - image[:,:,0]  # Invert the red channel
    image[:,:,1] = 255 - image[:,:,1]  # Invert the green channel
    image[:,:,2] = 255 - image[:,:,2]  # Invert the blue channel


    # Convert the NumPy array to a PyTorch tensor
    image = torch.from_numpy(image).type(torch.FloatTensor)

    # Make the plot
    fig, (ax1, ax2) = plt.subplots(figsize=(6,10), nrows=2)

    # Display the image
    ax1.imshow(image)
    ax1.axis('off')
    ax1.set_title(flower_title)

    # Plot the bar graph
    y_pos = np.arange(len(top_probs))
    ax2.barh(y_pos, top_probs, align='center')
    ax2.set_yticks(y_pos)
    ax2.set_yticklabels(top_labels)
    ax2.invert_yaxis()
    ax2.set_title('Class Probability')

    plt.tight_layout()
    plt.show()
    
    return
In [157]:
image_path = 'flowers/test/13/image_05775.jpg'
sanity_checker(image_path, cat_to_name)
[  9.99631464e-01   3.36321740e-04   1.56115857e-05   4.61144100e-06
   3.73245780e-06]
['king protea', 'fritillary', 'alpine sea holly', 'passion flower', 'spear thistle']
In [158]:
image_path = 'flowers/test/15/image_06351.jpg'
sanity_checker(image_path, cat_to_name)
[ 0.37096742  0.23321365  0.05728138  0.03853143  0.0338752 ]
['bird of paradise', 'bromelia', 'californian poppy', 'gazania', 'canna lily']
In [154]:
image_path = 'flowers/test/5/image_05159.jpg'
sanity_checker(image_path, cat_to_name)
[ 0.73361212  0.10860384  0.09040668  0.0521374   0.00974726]
['barbeton daisy', 'blanket flower', 'gazania', 'english marigold', 'orange dahlia']
In [155]:
image_path = 'flowers/test/2/image_05133.jpg'
sanity_checker(image_path, cat_to_name)
[  1.00000000e+00   4.14870616e-18   1.70182051e-18   7.28461712e-20
   6.81941979e-20]
['hard-leaved pocket orchid', 'windflower', 'hippeastrum', 'peruvian lily', 'moon orchid']
In [156]:
image_path = 'flowers/test/100/image_07902.jpg'
sanity_checker(image_path, cat_to_name)
[ 0.08514576  0.08479936  0.08280277  0.06506057  0.06282569]
['wallflower', 'orange dahlia', 'blanket flower', 'english marigold', 'gazania']

Reminder for Workspace users: If your network becomes very large when saved as a checkpoint, there might be issues with saving backups in your workspace. You should reduce the size of your hidden layers and train again.

We strongly encourage you to delete these large interim files and directories before navigating to another page or closing the browser tab.</font>

In [ ]:
# TODO remove .pth files or move it to a temporary `~/opt` directory in this Workspace
In [ ]: